// 监听来自content script的下载请求
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log("background收到消息:", message);
  if (message.action === "downloadMedia") {
    handleMediaDownload(message, sender, sendResponse); // 添加sender参数
    return true;
  }
});

// 修改handleMediaDownload函数定义和实现
function handleMediaDownload(message, sender, sendResponse) {
  // 添加sender参数
  try {
    let url = message.url;
    let fileName;
    let fileExtension;
    // 生成时间戳 (格式: 年月日时分秒)
    const timestamp = new Date()
      .toISOString()
      .replace(/[^0-9]/g, "")
      .slice(0, 14);

    if (message.isBase64 && message.type === "image") {
      // 处理base64图片
      fileExtension = message.imageType || "jpg";
      // 图片前缀 + 时间戳 + 扩展名
      fileName = `图片_${timestamp}.${fileExtension}`;
    } else {
      // 处理非base64媒体
      if (message.type === "image") {
        fileExtension = getImageExtension(url);
        // 图片前缀 + 时间戳 + 扩展名
        fileName = `图片_${timestamp}.${fileExtension}`;
      } else if (message.type === "video") {
        // 确定视频扩展名
        fileExtension = getVideoExtension(url) || "mp4";
        // 视频前缀 + 时间戳 + 扩展名
        fileName = `视频_${timestamp}.${fileExtension}`;
      } else {
        // 默认处理
        fileExtension = "mp4";
        fileName = `媒体_${timestamp}.${fileExtension}`;
      }
    }

    // 执行下载
    chrome.downloads.download(
      {
        url: url,
        filename: fileName,
        saveAs: false,
      },
      (downloadId) => {
        if (chrome.runtime.lastError) {
          console.error("下载失败:", chrome.runtime.lastError);
          sendResponse({
            success: false,
            error: chrome.runtime.lastError.message,
          });
        } else {
          console.log("下载成功，ID:", downloadId);
          sendResponse({ success: true, downloadId: downloadId });
        }
      }
    );
  } catch (error) {
    console.error("处理下载时出错:", error);
    sendResponse({ success: false, error: error.message });
  }
}

// 获取图片扩展名
function getImageExtension(url) {
  // 检查是否为base64图片
  if (url.startsWith("data:image/")) {
    const typeMatch = url.match(/data:image\/(\w+);/);
    if (typeMatch && typeMatch[1]) {
      return typeMatch[1];
    }
    return "jpg";
  }

  const extensionMatch = url.match(/\.([a-zA-Z0-9]+)(\?|$)/);
  if (
    extensionMatch &&
    ["jpg", "jpeg", "png", "gif", "webp"].includes(
      extensionMatch[1].toLowerCase()
    )
  ) {
    return extensionMatch[1].toLowerCase();
  }
  return "jpg";
}

// 添加视频扩展名获取函数
function getVideoExtension(url) {
  const extensionMatch = url.match(/\.([a-zA-Z0-9]+)(\?|$)/);
  if (
    extensionMatch &&
    ["mp4", "webm", "mov", "avi", "flv", "mkv", "wmv"].includes(
      extensionMatch[1].toLowerCase()
    )
  ) {
    return extensionMatch[1].toLowerCase();
  }
  return null; // 返回null让调用处处理默认值
}
